<?php

namespace App\Admin\Actions\Audit;

use App\Library\Logic\AmountLogic;
use App\Library\Logic\OperateLogLogic;
use App\Models\WithdrawModel;
use Encore\Admin\Actions\Response;
use Encore\Admin\Actions\RowAction;
use Encore\Admin\Facades\Admin;
use Exception;
use Illuminate\Http\Request;

class AuditWithdrawAction extends RowAction
{
    public $name = '审核';

    /**
     * handle
     * @param WithdrawModel $model
     * @param Request $request
     * @return Response
     * @throws Exception
     */
    public function handle(WithdrawModel $model, Request $request): Response
    {
        if ($model->status !== 0) return $this->response()->error(__('errorCode.633'))->refresh();
        else if ((int)$request->status === 1) $model->ok_reason = $request->reason;
        else if ((int)$request->status === 2) $model->fail_reason = $request->reason;
        $model->status = $request->status;
        $model->audit_at = now();
        $model->operate_id = Admin::user()->id;
        $model->save();
        if ((int)$request->status === 1) {
            mq('withdraw', $model);
            OperateLogLogic::add(Admin::user()->user_id, 'admin.withdraw.audit');
        }
        else {
            AmountLogic::insertForModelOfLock([
                'type' => 'withdraw',
                'userId' => $model->user_id,
                'title' => '提现失败',
                'objectType' => 'withdraw',
                'objectId' => $model->id,
                'amount' => (float)bcadd($model->amount, $model->fee, 2),
            ]);
        }
        return $this->response()->success('操作成功')->refresh();
    }

    public function form(): void
    {
        $this->select('status', __('withdraw.audit'))->options(__('withdraw.auditStatusArr'))->default(2)->required();
        $this->text('reason', '原因')->rules('nullable|string|max:255');
    }

    public function html(): string
    {
        return "<a class='report-posts btn btn-sm btn-danger'><i class='fa fa-info-circle'></i>确认</a>";
    }
}
